from flask import Flask, request, jsonify, render_template
from datetime import datetime
from nlp_chatbot import SimpleNLPChatbot 
import os 

app = Flask(__name__)

# 全局聊天机器人实例
chatbot = SimpleNLPChatbot()

@app.route('/')
def index():
    """主页"""
    return render_template('index.html')

@app.route('/health')
def health_check():
    """健康检查接口"""
    return jsonify({'status': 'healthy', 'timestamp': datetime.now().isoformat()})

@app.route('/chat', methods=['POST'])
def chat():
    """普通聊天接口"""
    try:
        data = request.get_json()
        user_message = data.get('message', '')
        
        if not user_message:
            return jsonify({'error': 'No message provided'}), 400
        
        # 调用聊天机器人
        response = chatbot.chat(user_message)
        
        return jsonify({
            'response': response,
            'timestamp': datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            'user_input': user_message
        })
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/enhanced_chat', methods=['POST'])
def enhanced_chat():
    """增强聊天接口（包含NLP分析）"""
    try:
        data = request.get_json()
        user_message = data.get('message', '')
        
        if not user_message:
            return jsonify({'error': 'No message provided'}), 400
        
        # 调用增强版聊天机器人
        result = chatbot.enhanced_chat(user_message)
        
        return jsonify(result)
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/history')
def get_history():
    """获取聊天历史"""
    try:
        return jsonify(chatbot.conversation_history)
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/clear', methods=['POST'])
def clear_history():
    """清空聊天历史"""
    try:
        chatbot.conversation_history = []
        return jsonify({'status': 'cleared', 'timestamp': datetime.now().isoformat()})
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/stats')
def get_stats():
    """获取统计信息"""
    try:
        # 这里可以返回聊天机器人的统计信息
        stats = {
            'total_conversations': 0,
            'intents_distribution': {},
            'server_start_time': datetime.now().isoformat(),
            'version': '1.0.0'
        }
        return jsonify(stats)
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

if __name__ == '__main__':
    # 确保响应文件存在
    if not os.path.exists('responses.json'):
        print("警告: responses.json 文件不存在，请创建该文件")
    
    if not os.path.exists('intent_keywords.json'):
        print("警告: intent_keywords.json 文件不存在，请创建该文件")
    
    print("🚀 启动NLP聊天机器人服务器...")
    print("📱 访问 http://localhost:5000 使用Web界面")
    print("🔧 API接口:")
    print("   POST /chat - 普通聊天")
    print("   POST /enhanced_chat - 增强分析聊天")
    print("   GET /history - 获取历史")
    print("   POST /clear - 清空历史")
    
    app.run(debug=True, host='0.0.0.0', port=5000)